﻿CREATE TRIGGER [dbo].[tr_LoanInfo_UPDATE]
ON [dbo].[t_LoanInfo]
FOR UPDATE
AS

IF @@ROWCOUNT = 0 RETURN

-- TODO: implement payment check for states with addon limitation
--IF UPDATE (PaymentOverride) BEGIN
--	DECLARE @PmtMax numeric(18,2),@PmtOver numeric(18,2)
--	SELECT @PmtMax = Payment_Max,@PmtOver = ISNULL(PaymentOverride,0) FROM v_LoanInfo
--	WHERE LoanID IN(SELECT LoanID FROM inserted) AND Payment_Max < PaymentOverride
--	IF @PmtMax < @PmtOver BEGIN
--		ROLLBACK TRAN
--		DECLARE @Text nvarchar(256) SET @Text = dbo.sprint2('Payment %s is greater than maximum %s, allowed by state.',@PmtOver,@PmtMax)
--		RAISERROR(@Text,16,1)
--		RETURN
--	END
--END

IF UPDATE(PaymentTypeID)
	UPDATE LI SET PaymentsPerYear = LPT.PaymentsPerYear
	FROM t_LoanInfo LI INNER JOIN inserted i ON LI.LoanID = i.LoanID
	INNER JOIN ts_LoanPaymentType LPT ON LI.PaymentTypeID = LPT.ID
	WHERE ISNULL(LI.PaymentsPerYear,0) <> LPT.PaymentsPerYear

IF UPDATE(PaymentsPerYear)
	UPDATE LI SET PaymentTypeID = LPT.ID
	FROM t_LoanInfo LI INNER JOIN inserted i ON LI.LoanID = i.LoanID
	INNER JOIN ts_LoanPaymentType LPT ON LI.PaymentsPerYear = LPT.PaymentsPerYear
	WHERE ISNULL(LI.PaymentTypeID,0) <> LPT.ID

IF (UPDATE(ContractDate) OR UPDATE(PaymentsPerYear)) AND NOT UPDATE(FirstPaymentDate)
	UPDATE t_LoanInfo SET FirstPaymentDate = dbo.NextPaymentDate(ContractDate,PaymentsPerYear,1)
	WHERE LoanID IN (SELECT LoanID FROM inserted)

